/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm),'');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function getDistanceInMeters(lat1, lng1, lat2, lng2) {
	console.log(lat1);
	console.log(lng1);
	console.log(lat2);
	console.log(lng2);
  const toRad = val => (val * Math.PI) / 180;
  const R = 6371000;
  const dLat = toRad(lat2 - lat1);
  const dLng = toRad(lng2 - lng1);
  const a =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
    Math.sin(dLng / 2) ** 2;
	console.log(a);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  console.log(c);
  return +(R * c).toFixed(2);
}

export function fetchStationCoordinates(latitude, longitude) {
  try {	
	if (latitude && longitude) {
	  const platform = uni.getSystemInfoSync().platform;

	  if (platform === "android" || platform === "ios") {
		uni.openLocation({
		  latitude: Number(latitude),
		  longitude: Number(longitude),
		  name: "电站位置",
		  address: "请使用地图查看详细位置",
		  scale: 18,
		  fail: (err) => {
			console.error("打开地图失败:", err);
			uni.showToast({
			  title: "打开地图失败",
			  icon: "none",
			});
		  },
		});
	  } else {
		const amapUrl = `https://uri.amap.com/marker?position=${longitude},${latitude}`;
		window.open(amapUrl, "_blank");
	  }
	} else {
	  uni.showToast({
		title: "未获取到位置信息",
		icon: "none",
	  });
	}
  } catch (error) {
	console.error("获取电站经纬度失败:", error);
	uni.showToast({
	  title: "获取位置失败",
	  icon: "none",
	});
  }
}

export function formatPicUrls (urls){
	return urls?.filter(Boolean)?.length  // 过滤掉 null/undefined/空字符串
    ? urls.map(url => ({ 
        url, 
        name: String(url).split('/').pop() 
      })) 
    : [];
}
  

